/**
 * Author(s): xuming.Wong <xuming.Wong@gmail.com>
 */
#include "ProjectManager.h"

#include "DataSerializer.h"
#include "FileSystem.h"

using namespace PQCore;
namespace PQEngine
{
	const std::string ProjectManager::PERSIS_FILE_NAME="Projects.gdt";
	ProjectManager::ProjectManager()
		: _projectIndex(0)
	{
		PQCore::SerializeParser parser(PERSIS_FILE_NAME);
		if(!parser.success()){
			return;
		}

		PQCore::SerializeDataId gname=parser.getName();
		
		if(gname==SerializeDataId_PersistProject){
			int size=parser.getParam()->getInt();
			
			for(int i=0;i<size;i++){
				_projectPathes.push_back(parser.getParam()->getString());
			}

		}

	}

	//Save scene is more suitable ?
	void ProjectManager::saveProject()
	{
		//ProjectSerializer::getSingleton().saveProject();
	}

	ProjectManager& ProjectManager::getSingleton()
	{
		static ProjectManager inst;
		return inst;
	}

	//create empty project
	bool ProjectManager::createProject(std::string path,std::string name)
	{
		std::string fullName=path+"/";
		fullName+=name;
		
		int size=_projectPathes.size();
		for(int i=0;i<size;i++){
			if(_projectPathes[i]==fullName){
				return false;//already exist
			}
		}
		if(FileSystem::isDirExist(fullName)){
			return false;//file folder already created.
		}

		_projectIndex=size;
		_projectPathes.push_back(_projectPath);
		
		persist();
		
		loadProject(_projectIndex);
		return true;
	}

	void ProjectManager::persist()
	{
		SerializeGenerator gen(SerializeDataId_PersistProject);
		int size=_projectPathes.size();
		gen.addIntParam(size);
		
		for(int i=0;i<size;i++){
			gen.addStringParam(_projectPathes[i]);
		}

		gen.serialize(PERSIS_FILE_NAME);
	}

	void ProjectManager::loadProject(int index)
	{
		_projectIndex=index;
		_projectPath=_projectPathes[index];

		_project=GameProject::get(_projectPath);
	}

	GPKArchive* ProjectManager::createAssetArchive(std::string name)
	{
		if(_project){
			return _project->createAssetArchive(name);
		}
		return 0;
	}


}
